package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.MainActivity;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.model.Picture;
import com.wdh.kjs.model.PictureRule;
import com.wdh.kjs.picker.AddressInitTask;
import com.wdh.kjs.util.PhonenumUtil;
import com.wdh.kjs.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by chenqinhuang on 2016/4/29.
 */
public class RongziActivity extends BaseTopActivity implements View.OnClickListener, TextWatcher {
    private EditText rongzi_name;
    private EditText rongzi_phone;
    private EditText rongzi_email;
    private TextView rongzi_address;
    private TextView rongzi_address_sheng;
    private TextView rongzi_address_shi;
    private TextView rongzi_address_xian;
    private EditText rongzi_title;
    private EditText rongzi_use;
    private EditText rongzi_source;
    private EditText rongzi_targetMoney;
    private EditText rongzi_AnnualizedBenefitRate;
    private EditText rongzi_companyName;
    private EditText rongzi_teamIntroduction;
    private View rongzi_line1;
    private View rongzi_line2;
    private RadioGroup rongzi_RadioGroup;
    private RadioButton rongzi_RadioButton1;
    private RadioButton rongzi_RadioButton2;
    private LinearLayout repayMode;
    private LinearLayout upload_file;
    private LinearLayout rongzi_companyName_LinearLayout;
    private LinearLayout rongzi_teamIntroduction_LinearLayout;
    private TextView choose_repay_mode_text;
    private Button saveSubmit;
    private Button saveDraft;
    private Intent intent;
    private JsonModel_my jsonModel_my;
    private String partyId;
    private String type;
    private String choose_repay_mode = "";
    private String itemType = "1";   //项目类型，0 股权众筹， 1 固定收益， 2 实物众筹， 3 公益众筹
    private String itemStatus = "1"; //项目状态  0 未提交 ，1 待审核，2 资料待补充，3 待美工，4 待发送 ，5 待确认上线，6 上线失败， 7 众筹中， 8 预热中，9 众筹成功 ，10 募集失败 11 逾期
    private String gdItemType = "";  //固定收益子项目 0 政信资产贷，1 中小企业担保贷，2 物权质押贷，3 普惠三农贷，4 消费金融贷
    private String repay_mode = "";  //收益方式 0 到期一次性还本付息 , 1 按月付息到期还本
    private String gdIfPledge = "";  //是否有质押物 ，0 无 1 有
    private ImageView iv_dizhixuanzhe;
    private AddressInitTask addressInitTask;
    private Picture picture;
    private List<String> idList = new ArrayList<String>();

    private TextView rongzi_address_sheng_youbian;
    private TextView rongzi_address_shi_youbian;
    private TextView rongzi_address_xian_youbian;
    /**
     * 基础信息
     */
    private List<String> listString = new ArrayList<>();
    /**
     * 财力证明
     */
    private List<String> moneyString = new ArrayList<>();
    /**
     * 征信证明
     */
    private List<String> zhengString = new ArrayList<>();
    /**
     * 相关法律材料
     */
    private List<String> lawString = new ArrayList<>();
    /**
     * 其他补充材料
     */
    private List<String> otherString = new ArrayList<>();
    /**
     * 财务报表材料
     */
    private List<String> caiwuString = new ArrayList<>();
    /**
     * 财力产权证明
     */
    private List<String> cailiString = new ArrayList<>();
    /**
     * 经营情况材料
     */
    private List<String> jingyingString = new ArrayList<>();
    /**
     * 用户类型
     */
    private final static String PERSON = "p";
    private final static String NONE = "n";
    private final static String ORGANIZATION = "o";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rongzimessage);
        initTopBar("填写融资信息");
        SharedPreferences sharedPreferences = getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = sharedPreferences.getString("loginToken", "");
        type = sharedPreferences.getString("type", "");

        intent = getIntent();
        gdItemType = intent.getStringExtra("gdItemType");
        initview();
        rongzi_AnnualizedBenefitRate.addTextChangedListener(this);
    }

    private void getIdList() {
        SharedPreferences mysharedPreferences = getSharedPreferences("zhaopian", MODE_PRIVATE);
        String jsonId = mysharedPreferences.getString("jsonId", "");
        String zhengId = mysharedPreferences.getString("zhengId", "");
        String lawId = mysharedPreferences.getString("lawId", "");
        String otherId = mysharedPreferences.getString("otherId", "");
        String moneyId = mysharedPreferences.getString("moneyId", "");
        if (!jsonId.equals("")) {
            listString = JSON.parseArray(jsonId, String.class);
            for (int i = 0; i < listString.size(); i++) {
                idList.add(listString.get(i));
            }
        }
        if (!moneyId.equals("")) {
            moneyString = JSON.parseArray(moneyId, String.class);
            for (int i = 0; i < moneyString.size(); i++) {
                idList.add(moneyString.get(i));
            }
        }
        if (!zhengId.equals("")) {
            zhengString = JSON.parseArray(zhengId, String.class);
            for (int i = 0; i < zhengString.size(); i++) {
                idList.add(zhengString.get(i));
            }
        }
        if (!lawId.equals("")) {
            lawString = JSON.parseArray(lawId, String.class);
            for (int i = 0; i < lawString.size(); i++) {
                idList.add(lawString.get(i));
            }
        }
        if (!otherId.equals("")) {
            otherString = JSON.parseArray(otherId, String.class);
            for (int i = 0; i < otherString.size(); i++) {
                idList.add(otherString.get(i));
            }
        }

    }

    private void loadData() {
        RequestParams params = new RequestParams();
        //暂时没加上地址、上传文件
        params.addBodyParameter("itemStatus", itemStatus);
        params.addBodyParameter("partyId", partyId);

        params.addBodyParameter("localProvince", rongzi_address_sheng.getText() + "");
        params.addBodyParameter("localCity", rongzi_address_shi.getText() + "");
        params.addBodyParameter("localCounty", rongzi_address_xian.getText() + "");


        params.addBodyParameter("contactName", rongzi_name.getText().toString());
        params.addBodyParameter("contactTel", rongzi_phone.getText().toString());
        params.addBodyParameter("contactEmail", rongzi_email.getText().toString());
        params.addBodyParameter("companyName", rongzi_companyName.getText().toString());
        params.addBodyParameter("teamIntroduction", rongzi_teamIntroduction.getText().toString());
        params.addBodyParameter("itemName", rongzi_title.getText().toString());
        params.addBodyParameter("gdFinancingRequired", rongzi_use.getText().toString());
        params.addBodyParameter("gdSrcOfRepayment", rongzi_source.getText().toString());
        params.addBodyParameter("gdIfPledge", gdIfPledge);
        params.addBodyParameter("targetMoney", rongzi_targetMoney.getText().toString());
        params.addBodyParameter("gdAnnualizedBenefitRate", rongzi_AnnualizedBenefitRate.getText().toString());
        params.addBodyParameter("gdBenefitMode", repay_mode);
        params.addBodyParameter("itemType", itemType);
        params.addBodyParameter("gdItemType", gdItemType);
        params.addBodyParameter("docList", JSON.toJSONString(picture));

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LAUNCH_IYEM, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.success) {
                    falseDialogShow("项目提交成功，请等待审核！");
//                    ToastUtils.showShort(RongziActivity.this, "项目提交成功，请等待审核！");
                    if (PERSON.equals(type)) {
                        clearPerInf();
                    } else if (ORGANIZATION.equals(type)) {
                        clearOrgInf();
                    }
                    intent = new Intent(RongziActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(RongziActivity.this, "网络异常！");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.repayMode:
                intent = new Intent(this, ChooseRepayModeActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.upload_file:
                /*intent = new Intent(this, UploadProjectInfoActivity.class);
                startActivityForResult(intent, 0);
                intent = new Intent(this, UploadProjectInfoOrgActivity.class);
                startActivityForResult(intent, 1);*/
                if (PERSON.equals(type)) {
                    intent = new Intent(this, UploadProjectInfoActivity.class);
                    startActivityForResult(intent, 0);
                } else if (ORGANIZATION.equals(type)) {
                    intent = new Intent(this, UploadProjectInfoOrgActivity.class);
                    startActivityForResult(intent, 1);
                }
                break;
            case R.id.saveSubmit:
                if (PERSON.equals(type)) {
                    getIdList();
                    picture = new Picture();
                    for (int i = 0; i < idList.size(); i++) {
                        picture.addUserData(new PictureRule(idList.get(i)));
                    }
                    checkAllPer();
                } else if (ORGANIZATION.equals(type)) {
                    getOrgIdList();
                    picture = new Picture();
                    for (int i = 0; i < idList.size(); i++) {
                        picture.addUserData(new PictureRule(idList.get(i)));
                    }
                    checkAllOrg();
                }
                break;
//            case R.id.saveDraft:
//                ToastUtils.showShort(RongziActivity.this, "保存草稿—敬请期待！");
//                break;
//            case R.id.upload_projectInfo:
//                intent = new Intent(this,UploadProjectInfoActivity.class);
//                startActivity(intent);
//                break;
//            case R.id.check_neededInfo:
//                intent = new Intent(this,CheckNeededInfoActivity.class);
//                startActivity(intent);
//                break;
            case R.id.iv_dizhixuanzhe:
                addressInitTask = new AddressInitTask(this, rongzi_address_sheng, rongzi_address_shi, rongzi_address_xian, rongzi_address_sheng_youbian, rongzi_address_shi_youbian, rongzi_address_xian_youbian);
                addressInitTask.execute("福建", "福州", "晋安");
                break;
            default:
                break;
        }

    }

    private void initview() {
        rongzi_address_sheng = (TextView) findViewById(R.id.rongzi_address_sheng);
        rongzi_address_shi = (TextView) findViewById(R.id.rongzi_address_shi);
        rongzi_address_xian = (TextView) findViewById(R.id.rongzi_address_xian);
        rongzi_address_sheng_youbian = (TextView) findViewById(R.id.rongzi_address_sheng_youbian);
        rongzi_address_shi_youbian = (TextView) findViewById(R.id.rongzi_address_shi_youbian);
        rongzi_address_xian_youbian = (TextView) findViewById(R.id.rongzi_address_xian_youbian);
        rongzi_name = (EditText) findViewById(R.id.rongzi_name);
        rongzi_phone = (EditText) findViewById(R.id.rongzi_phone);
        rongzi_email = (EditText) findViewById(R.id.rongzi_email);
//        rongzi_address = (TextView) findViewById(R.id.rongzi_address);
        rongzi_title = (EditText) findViewById(R.id.rongzi_title);
        rongzi_use = (EditText) findViewById(R.id.rongzi_use);
        rongzi_source = (EditText) findViewById(R.id.rongzi_source);
        rongzi_targetMoney = (EditText) findViewById(R.id.rongzi_targetMoney);
        rongzi_AnnualizedBenefitRate = (EditText) findViewById(R.id.rongzi_AnnualizedBenefitRate);
        rongzi_companyName = (EditText) findViewById(R.id.rongzi_companyName);
        rongzi_teamIntroduction = (EditText) findViewById(R.id.rongzi_teamIntroduction);
        choose_repay_mode_text = (TextView) findViewById(R.id.choose_repay_mode_text);
        iv_dizhixuanzhe = (ImageView) findViewById(R.id.iv_dizhixuanzhe);

        rongzi_companyName_LinearLayout = (LinearLayout) findViewById(R.id.rongzi_companyName_LinearLayout);
        rongzi_teamIntroduction_LinearLayout = (LinearLayout) findViewById(R.id.rongzi_teamIntroduction_LinearLayout);
        rongzi_line1 = findViewById(R.id.rongzi_line1);
        rongzi_line2 = findViewById(R.id.rongzi_line2);
        if (type.equals("o")) {
            rongzi_companyName_LinearLayout.setVisibility(View.VISIBLE);
            rongzi_teamIntroduction_LinearLayout.setVisibility(View.VISIBLE);
            rongzi_line1.setVisibility(View.VISIBLE);
            rongzi_line2.setVisibility(View.VISIBLE);
        }

        saveSubmit = (Button) findViewById(R.id.saveSubmit);
        saveSubmit.setOnClickListener(this);
//        saveDraft = (Button) findViewById(R.id.saveDraft);
//        saveDraft.setOnClickListener(this);
        repayMode = (LinearLayout) findViewById(R.id.repayMode);
        repayMode.setOnClickListener(this);
        upload_file = (LinearLayout) findViewById(R.id.upload_file);
        upload_file.setOnClickListener(this);
        iv_dizhixuanzhe.setOnClickListener(this);
        rongzi_RadioGroup = (RadioGroup) findViewById(R.id.rongzi_RadioGroup);
        rongzi_RadioButton1 = (RadioButton) findViewById(R.id.rongzi_RadioButton1);
        rongzi_RadioButton2 = (RadioButton) findViewById(R.id.rongzi_RadioButton2);
        rongzi_RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (rongzi_RadioButton1.getId() == i) {
                    gdIfPledge = "1";
                    ToastUtils.showShort(RongziActivity.this, "有！");
                } else if (rongzi_RadioButton2.getId() == i) {
                    ToastUtils.showShort(RongziActivity.this, "否！");
                    gdIfPledge = "0";
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (resultCode == 2) {
                choose_repay_mode = data.getStringExtra("choose_repay_mode");
                choose_repay_mode_text.setText(choose_repay_mode);
                switch (choose_repay_mode) {
                    case "到期一次性还本付息":
                        repay_mode = "0";
                        break;
                    case "按月付息到期还本":
                        repay_mode = "1";
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void falseDialogShow(String hint) {
        View dialog = getLayoutInflater().inflate(R.layout.touzixinxi, null);
//        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
//        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.touzixinxi);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        tv_dialog_false_hint.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
//        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dialogShow.dismiss();
//            }
//        });
    }

    private void getOrgIdList() {
        idList = new ArrayList<>();
        SharedPreferences mysharedPreferences = getSharedPreferences("orgzhaopian", MODE_PRIVATE);
        String jsonId = mysharedPreferences.getString("jsonId", "");
        String jingyingId = mysharedPreferences.getString("jingyingId", "");
        String zhengId = mysharedPreferences.getString("zhengId", "");
        String cailiId = mysharedPreferences.getString("cailiId", "");
        String caiwuId = mysharedPreferences.getString("caiwuId", "");
        String lawId = mysharedPreferences.getString("lawId", "");
        String otherId = mysharedPreferences.getString("otherId", "");
        if (!jsonId.equals("")) {
            listString = JSON.parseArray(jsonId, String.class);
            for (int i = 0; i < listString.size(); i++) {
                idList.add(listString.get(i));
            }
        }
        if (!jingyingId.equals("")) {
            jingyingString = JSON.parseArray(jingyingId, String.class);
            for (int i = 0; i < jingyingString.size(); i++) {
                idList.add(jingyingString.get(i));
            }
        }
        if (!zhengId.equals("")) {
            zhengString = JSON.parseArray(zhengId, String.class);
            for (int i = 0; i < zhengString.size(); i++) {
                idList.add(zhengString.get(i));
            }
        }
        if (!cailiId.equals("")) {
            cailiString = JSON.parseArray(cailiId, String.class);
            for (int i = 0; i < cailiString.size(); i++) {
                idList.add(cailiString.get(i));
            }
        }
        if (!caiwuId.equals("")) {
            caiwuString = JSON.parseArray(caiwuId, String.class);
            for (int i = 0; i < caiwuString.size(); i++) {
                idList.add(caiwuString.get(i));
            }
        }
        if (!lawId.equals("")) {
            lawString = JSON.parseArray(lawId, String.class);
            for (int i = 0; i < lawString.size(); i++) {
                idList.add(lawString.get(i));
            }
        }
        if (!otherId.equals("")) {
            otherString = JSON.parseArray(otherId, String.class);
            for (int i = 0; i < otherString.size(); i++) {
                idList.add(otherString.get(i));
            }
        }
    }

    private void checkAllPer() {
        System.out.println("checkAllPer");
        if (rongzi_name.getText().toString().equals(""))
            falseDialogShow("请输入姓名");
        else if (rongzi_phone.getText().toString().equals("")) {
            falseDialogShow("请输入电话");
        } else if (!PhonenumUtil.isMobileNO(rongzi_phone.getText().toString())) {
            falseDialogShow("请输入正确的电话号码");
        } else if (rongzi_email.getText().toString().equals("")) {
            falseDialogShow("请输入邮箱");
        } else if (!PhonenumUtil.checkEmail(rongzi_email.getText().toString())) {
            falseDialogShow("请输入正确的邮箱");
        } else if (rongzi_address_sheng_youbian.getText().equals(""))
            falseDialogShow("请选择地址");
        else if (rongzi_title.getText().toString().equals(""))
            falseDialogShow("请输入项目名称");
        else if (rongzi_use.getText().toString().equals(""))
            falseDialogShow("请输入借款用途");
        else if (rongzi_source.getText().toString().equals(""))
            falseDialogShow("请输入还款来源");
        else if (rongzi_targetMoney.getText().toString().equals(""))
            falseDialogShow("请输入目标融资金额");
        else if (rongzi_AnnualizedBenefitRate.getText().toString().equals(""))
            falseDialogShow("请输入预期年化收益率");
        else if (JSON.toJSONString(picture).toString().equals("{}"))
            falseDialogShow("请上传相关材料");
        else
            loadData();
    }

    private void checkAllOrg() {
        System.out.println("checkAllOrg");
        if (rongzi_name.getText().toString().equals(""))
            falseDialogShow("请输入姓名");
        else if (rongzi_phone.getText().toString().equals("")) {
            falseDialogShow("请输入电话");
        } else if (!PhonenumUtil.isMobileNO(rongzi_phone.getText().toString())) {
            falseDialogShow("请输入正确的电话号码");
        } else if (rongzi_email.getText().toString().equals("")) {
            falseDialogShow("请输入邮箱");
        } else if (!PhonenumUtil.checkEmail(rongzi_email.getText().toString())) {
            falseDialogShow("请输入正确的邮箱");
        } else if (rongzi_address_sheng_youbian.getText().equals(""))
            falseDialogShow("请选择地址");
        else if (rongzi_companyName.getText().toString().equals("")) {
            falseDialogShow("请输入公司全称");
        } else if (rongzi_teamIntroduction.getText().toString().equals("")) {
            falseDialogShow("请输入公司简介");
        } else if (rongzi_title.getText().toString().equals(""))
            falseDialogShow("请输入项目名称");
        else if (rongzi_use.getText().toString().equals(""))
            falseDialogShow("请输入借款用途");
        else if (rongzi_source.getText().toString().equals(""))
            falseDialogShow("请输入还款来源");
        else if (rongzi_targetMoney.getText().toString().equals(""))
            falseDialogShow("请输入目标融资金额");
        else if (rongzi_AnnualizedBenefitRate.getText().toString().equals(""))
            falseDialogShow("预期年化收益率");
        else if (JSON.toJSONString(picture).toString().equals("{}"))
            falseDialogShow("请上传相关材料");
        else
            loadData();
    }

    private void clearOrgInf() {
        SharedPreferences.Editor editor = getSharedPreferences("orgzhaopian", MODE_PRIVATE).edit();
        editor.putString("jichusize", "0");
        editor.putString("jingyingsize", "0");
        editor.putString("zhengxinsize", "0");
        editor.putString("cailisize", "0");
        editor.putString("caiwusize", "0");
        editor.putString("lawsize", "0");
        editor.putString("othersize", "0");
        editor.putString("jichu", "");
        editor.putString("jingying", "");
        editor.putString("zhengxin", "");
        editor.putString("caili", "");
        editor.putString("caiwu", "");
        editor.putString("law", "");
        editor.putString("other", "");
        editor.putString("jsonId", "");
        editor.putString("jingyingId", "");
        editor.putString("zhengId", "");
        editor.putString("cailiId", "");
        editor.putString("caiwuId", "");
        editor.putString("lawId", "");
        editor.putString("otherId", "");
        editor.clear();
        editor.commit();
    }

    private void clearPerInf() {
        SharedPreferences.Editor editor = getSharedPreferences("zhaopian", MODE_PRIVATE).edit();
        editor.putString("jichusize", "0");
        editor.putString("othersize", "0");
        editor.putString("lawsize", "0");
        editor.putString("zhengxinsize", "0");
        editor.putString("moneysize", "0");
        editor.putString("law", "");
        editor.putString("jichu", "");
        editor.putString("caili", "");
        editor.putString("zhengxin", "");
        editor.putString("other", "");
        editor.putString("jsonId", "");
        editor.putString("moneyId", "");
        editor.putString("zhengId", "");
        editor.putString("lawId", "");
        editor.putString("otherId", "");
        editor.commit();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String m = rongzi_AnnualizedBenefitRate.getText().toString();
        String[] list = m.split("");
        for (int i=0;i<list.length;i++){
            if (list[i].equals(".")){
                if (list.length-i>3){
                    falseDialogShow("请输入正确的预期年化收益率");
                    rongzi_AnnualizedBenefitRate.setText("");
                }
            }
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
